package huawei.dpoint;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * https://leetcode-cn.com/problems/string-compression/
 */
public class J443 {
    public static void main(String [] args){
        System.out.println(compress2("aabbccc".toCharArray()));
        System.out.println(compress2("aaabbaa".toCharArray()));
        System.out.println(compress2("aabbccc".toCharArray()));
    }
    public static int compress(char[] chars) {
        if(chars==null||chars.length==0){
            return 0;
        }
        int i =0;
        int len = chars.length;
        while (i<len) {
            char cur = chars[i];
            int endIndex =i+1;
            while (endIndex<len&&chars[endIndex]==cur){
                endIndex++;
            }
            if(endIndex-i==1){
                // 只有一个不用动.
                i++;
            }else {
                String count =String.valueOf(endIndex-i);
                // 填充内容
                for (int j = 0; j <count.length() ; j++) {
                    chars[i+1+j]=count.charAt(j);
                }
                // 移动字串
                int nextIndex=i+count.length()+1;
                for (int j = endIndex; j < len; j++) {
                    chars[j+nextIndex-endIndex]=chars[j];
                }
                len -= (endIndex-nextIndex);
                i=nextIndex;
            }
        }
        System.out.println(Arrays.toString(chars));
        return len;
    }
    public static int compress2(char[] chars) {
        int write =0;
        char c = chars[0];
        int count = 1;
        for (int read = 1; read < chars.length; read++) {
            if(chars[read]==c){
                count++;
            }else {
                chars[write++]=c;
                if(count>1){
                    String cStr=String.valueOf(count);
                    for(char cs:cStr.toCharArray()){
                        chars[write++]=cs;
                    }
                }
                count=1;
                c=chars[read];
            }
        }
        chars[write++]=c;
        if(count>1){
            String cStr=String.valueOf(count);
            for(char cs:cStr.toCharArray()){
                chars[write++]=cs;
            }
        }
        return write;
    }
}
